package chapter03;

/**
 * 通过只调整链来交换两个相邻的元素，使用
 * a. 单链表
 * b. 双链表
 */
public class Q2 {

    /**
     * For single linded list.
     * beforeP is the cell before the two adjacent cells thats are to be swapped.
     * @param beforep
     */
    public static void swapWithNext(Node beforep) {
        Node p, afterp;
        p = beforep.next;
        afterp = p.next; // Both p and afterp assumed not null

        p.next = afterp.next;
        afterp.next = p;
        beforep.next = afterp;
    }

    /**
     * For doubly linked lists:
     * p and afterp are cells to be swithed. Error checks as before.
     * @param p
     */
    public static void swapWithNext2(Node p) {
        Node beforep, afterp;

        beforep = p.prev;
        afterp = p.next;

        p.next = afterp.next;
        afterp.next = p;
        beforep.next = afterp;

        afterp.prev = beforep;
        p.prev = afterp;
        //afterp.next.prev = p; 这个不对，因为上述afterp.next已经调整指向
        p.next.prev = p;
    }

}
